package com.ljb.demo.v;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioGroup;

import com.ljb.demo.R;

public class MainActivity extends FragmentActivity {

    private FragmentManager fm;
    private RadioGroup rg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUI();
    }

    private void initUI() {
        //获取FragmentManager
        fm = getSupportFragmentManager();
        //获取radioGroup控件
        rg = (RadioGroup) findViewById(R.id.rg_tab);
        //监听点击按钮事件,实现不同Fragment之间的切换
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                Fragment fragment = getFragment(checkedId);
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.fl_container, fragment);
                ft.commit();
            }
        });
        rg.check(R.id.rb1);
    }


    //获取Fragment
    private Fragment getFragment(@IdRes int checkedId) {
        Fragment fragment = null;
        switch (checkedId) {
            case R.id.rb1:
                fragment = new Fragment1();
                break;
            case R.id.rb2:
                fragment = new Fragment2();
                break;
            case R.id.rb3:
                fragment = new Fragment3();
                break;
            case R.id.rb4:
                fragment = new Fragment4();
                break;
        }
        return fragment;
    }
}
